package com.wtwd.campus.receiver;

import com.alibaba.fastjson.JSONObject;
import com.wtwd.campus.annotation.MsgType;
import com.wtwd.campus.common.Constants;
import com.wtwd.campus.dao.CommandRecordMapper;
import com.wtwd.campus.dao.DeviceClassPatternMapper;
import com.wtwd.campus.dao.DeviceInfoMapper;
import com.wtwd.campus.entity.*;
import com.wtwd.campus.h5_manager.entity.DeviceLog;
import com.wtwd.campus.h5_manager.service.DeviceLogService;
import com.wtwd.campus.utils.ReceiverUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;

/**
 * @author mjy
 * @date 2021/06/25
 * @description
 */
@Service
@MsgType(value = Constants.SET_NO_DISTURB_TIME)
public class ReceiveClassModeHandler implements IReceiverHandler {
    @Autowired
    private DeviceClassPatternMapper deviceClassPatternMapper;
    @Autowired
    private CommandRecordMapper commandRecordMapper;
    @Autowired
    private DeviceInfoMapper deviceInfoMapper;
    @Autowired
    private ReceiverUtils receiverUtils;
    @Autowired
    private DeviceLogService deviceLogService;
    @Override
    public void handlerMessage(MqMessage mqMessage) {
        MqClassModeResult mqClassModeResult = (MqClassModeResult) mqMessage.getObject();
        ArrayList<String> commandTypeList = new ArrayList<>();
        commandTypeList.add(Constants.DEL_CLASS_MODE);
        commandTypeList.add(Constants.SET_NO_DISTURB_TIME);
        commandTypeList.add(Constants.UPDATE_CLASS_MODE);
        String value = mqClassModeResult.getValue();
        Integer sequence = mqClassModeResult.getSequence();
        String commandNumber = mqClassModeResult.getCommandNumber();
        String imei = mqClassModeResult.getImei();
        // 解析value成正常数据
        String beginTime = value.substring(0, 2).concat(":").concat(value.substring(2, 4));
        String endTime = value.substring(4, 6).concat(":").concat(value.substring(6, 8));
        String repeatTime = "";
        for (int i = 1; i <= 7; i++) {
            repeatTime = repeatTime.concat(value.substring(7 + i*2,8+i*2));
        }
        //根据课程表和imei号找到唯一的一条指令记录
        CommandRecord commandRecord = commandRecordMapper.getCommandRecordByCondition(imei, sequence, commandTypeList,commandNumber);
        //指令发送记录不存在，不处理
        if (commandRecord != null) {
            //鉴别是否是当前指令，不是当前指令不处理
            if (commandRecord.getCommandNumber().equals(commandNumber)) {
                DeviceInfo deviceInfo = deviceInfoMapper.getDeviceInfoByImei(mqClassModeResult.getImei());
                if (deviceInfo != null) {
                    //删除
                    if (commandRecord.getCommandType().equals(Constants.DEL_CLASS_MODE)) {
                        deviceClassPatternMapper.delClassPattern(deviceInfo.getDeviceId(), mqClassModeResult.getSequence());
                    }
                    // 修改 或 新增
                    else{
                        addOrUpdateClassMode(deviceInfo.getDeviceId(),sequence,imei,beginTime,endTime,repeatTime,commandNumber);
                    }
                    //将指令状态改为完成
                    commandRecordMapper.completeCommand(commandRecord.getId(), System.currentTimeMillis());
                    //如果定位数据不为空,则处理定位数据
                    LocationDataVo locationDataVo = null;
                    if (mqClassModeResult.getMqLocationData() != null) {
                        //处理指令回复的时间
                        String deviceDate = mqClassModeResult.getDeviceDate();
                        String deviceTime = mqClassModeResult.getDeviceTime();
                        Long time = getTime(deviceDate, deviceTime);
                        MqLocationData mqLocationData = mqClassModeResult.getMqLocationData();
                        if(mqLocationData != null){
                            if (mqLocationData.getLatitude() != 0 && mqLocationData.getLongitude() != 0) {
                                //进行定位数据存储以及围栏告警记录的存储
                                deviceInfo = receiverUtils.dealLocation(mqClassModeResult.getMqLocationData(),  time, deviceInfo,1);
                                locationDataVo = new LocationDataVo();
                                locationDataVo.setLocationType(1);
                                locationDataVo.setLatitude(mqClassModeResult.getMqLocationData().getLatitude().toString());
                                locationDataVo.setLongitude(mqClassModeResult.getMqLocationData().getLongitude().toString());
                                locationDataVo.setAddress(deviceInfo.getAddress());
                                locationDataVo.setImei(imei);
                                locationDataVo.setLocationTime(time);
                            }
                        }
                    }
                    //更新设备最后上传时间
                    deviceInfo.setLastUpTime(System.currentTimeMillis());
                    deviceInfoMapper.updateDeviceInfo(deviceInfo);
                    //删除缓存中的指令
                    String delKey = Constants.SET_NO_DISTURB_TIME.concat("-").concat(mqClassModeResult.getCommandNumber().concat("-").concat(String.valueOf(sequence)));
                    receiverUtils.deleteCommandInRedis(mqClassModeResult.getImei(), delKey);
                    //存储设备接收日志
                    DeviceLog deviceLog = new DeviceLog();
                    deviceLog.setSendUser(Constants.DEVICE_USER);
                    deviceLog.setImei(imei);
                    deviceLog.setBigType(Constants.MESS_TYPE);
                    deviceLog.setType(Constants.SET_NO_DISTURB_TIME);
                    JSONObject contant = new JSONObject();
                    contant.put("设备号", imei);
                    contant.put("组号",sequence);
                    contant.put("内容",value);
                    contant.put("日期",mqClassModeResult.getDeviceDate());
                    contant.put("经度", mqClassModeResult.getMqLocationData().getLongitude());
                    contant.put("纬度", mqClassModeResult.getMqLocationData().getLatitude());
                    contant.put("时间", mqClassModeResult.getDeviceTime());
                    contant.put("设备状态",mqClassModeResult.getDeviceStatus());
                    deviceLog.setCmd(contant.toJSONString());
                    deviceLog.setSendTime(System.currentTimeMillis());
                    deviceLog.setCommandNumber(commandNumber);
                    deviceLog.setState(1);
                    deviceLogService.addDeviceLog(deviceLog);
                } else {
                    saveUnInStorage(imei);
                    receiverUtils.cloaseChannel(imei);
                }
            }
        }
    }

    public void addOrUpdateClassMode(Integer deviceId,Integer sequence,String imei,String beginTime,String endTime,String repeatTime,String commandNumber){
        DeviceClassPattern deviceClassPattern = deviceClassPatternMapper.getClassPatternByDeviceIdAndSequence(deviceId,sequence);
        if(deviceClassPattern == null){
            DeviceClassMode deviceClassMode = new DeviceClassMode();
            deviceClassMode.setImei(imei);
            deviceClassMode.setSequence(sequence);
            deviceClassMode.setDeviceId(deviceId);
            deviceClassMode.setStartTime(beginTime);
            deviceClassMode.setEndTime(endTime);
            deviceClassMode.setRepeatTime(repeatTime);
            deviceClassMode.setOnOff(1);
            deviceClassMode.setStatus(Constants.CLASSES_PATTERN_NORMAl);
            deviceClassPatternMapper.addDeviceClassPattern(deviceClassMode);
        }else{
            if(commandNumber.equalsIgnoreCase(deviceClassPattern.getCommandNumber())){
                commandNumber = null;
            }
            deviceClassPatternMapper.updateDeviceClassMode(deviceId,sequence,beginTime,endTime,repeatTime,commandNumber,Constants.CLASSES_PATTERN_NORMAl);
        }
    }
}


